﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

namespace OfficeExport
{
    public class ExcelExportor:IExportor
    {
        #region Ctor

        public ExcelExportor()
        {
            Application = new Excel.ApplicationClass();
        }

        #endregion

        #region Properties

        public Excel.Application Application
        {
            get;
            protected set;
        }

        #endregion

        #region IExportor Interface

        public void ExportTo(string fileFullName, ExportType exportType)
        {
            int index = fileFullName.LastIndexOf(".");
            if (index > -1)
            {
                string exportFullName = fileFullName.Substring(0, index) + ExportorFactory.GetExportFileExtension(exportType);
                ExportTo(fileFullName, exportFullName, exportType);
            }
        }

        public void ExportTo(string fileFullName, string exportFullName, ExportType exportType)
        {
            Excel.Workbook workBook = null;
            try
            {
                int index = fileFullName.LastIndexOf(".");
                string fileExtension = fileFullName.Substring(index, fileFullName.Length - index);
                object openFileFormat = ExportorFactory.GetOpenFileFormat<ExcelExportor>(fileExtension);
                object openMissing = Type.Missing;
                workBook = Application.Workbooks.Open(fileFullName, openMissing, openMissing, openMissing, openMissing, openMissing,
                        openMissing, openMissing, openMissing, openFileFormat, openMissing, openMissing, openMissing, openMissing, openMissing);

                if (workBook != null)
                {
                    string exportFileName = fileFullName.Substring(0, index) + ExportorFactory.GetExportFileExtension(exportType);
                    Excel.XlFixedFormatType exportFileForamt = (Excel.XlFixedFormatType)ExportorFactory.GetExportFormat<ExcelExportor>(exportType);
                    object saveMissing = Type.Missing;
                    workBook.ExportAsFixedFormat(exportFileForamt, exportFileName);
                    workBook.Close();
                }
            }
            catch (Exception error)
            {
            }
            finally
            {
                if (workBook != null)
                {
                    Marshal.ReleaseComObject(workBook);
                    GC.Collect();
                }
            }
        }

        public void Dispose()
        {
            Marshal.ReleaseComObject(Application);
            GC.Collect();
        }
        #endregion
    }
}
